package projetsia.com.hairhunter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;




public class FavorisListActivity extends ListActivity {

    private GetFavorisTask mFavorisTask;
    List<Favoris> list = new ArrayList<Favoris>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle objetbunble = this.getIntent().getExtras();
        // récupération de la valeur
        String userId= objetbunble .getString("userId");

        mFavorisTask = new GetFavorisTask();
        mFavorisTask.execute(userId);



    }

       public class GetFavorisTask extends AsyncTask<String, Void, String> {


        GetFavorisTask() {

        }

        @Override
        protected String doInBackground(String... params) {


            HttpClient httpClient = new DefaultHttpClient();
            String uId = params[0];


            System.out.println("UserId "+uId);

            // In a POST request, we don't pass the values in the URL.
            //Therefore we use only the web page URL as the parameter of the HttpPost argument
            HttpPost httpPost = new HttpPost("http://hairhunter.kilu.de/index.php");

            BasicNameValuePair userIdBasicNameValuePAir = new BasicNameValuePair("userId", uId);
            BasicNameValuePair tagBasicNameValuePAir = new BasicNameValuePair("tag", "favorisList");

            // We add the content that we want to pass with the POST request to as name-value pairs
            //Now we put those sending details to an ArrayList with type safe of NameValuePair
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
            nameValuePairList.add(tagBasicNameValuePAir);
            nameValuePairList.add(userIdBasicNameValuePAir);

            try {
                // UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs.
                //This is typically useful while sending an HTTP POST request.
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);

                // setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
                httpPost.setEntity(urlEncodedFormEntity);

                try {
                    // HttpResponse is an interface just like HttpPost.
                    //Therefore we can't initialize them
                    HttpResponse httpResponse = httpClient.execute(httpPost);

                    // According to the JAVA API, InputStream constructor do nothing.
                    //So we can't initialize InputStream although it is not an interface
                    InputStream inputStream = httpResponse.getEntity().getContent();

                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                    StringBuilder stringBuilder = new StringBuilder();

                    String bufferedStrChunk = null;

                    while((bufferedStrChunk = bufferedReader.readLine()) != null){
                        stringBuilder.append(bufferedStrChunk);
                    }

                    return stringBuilder.toString();

                } catch (ClientProtocolException cpe) {
                    System.out.println("First Exception caz of HttpResponese :" + cpe);
                    cpe.printStackTrace();
                } catch (IOException ioe) {
                    System.out.println("Second Exception caz of HttpResponse :" + ioe);
                    ioe.printStackTrace();
                }

            } catch (UnsupportedEncodingException uee) {
                System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
                uee.printStackTrace();
            }

            return null;
        }


        @Override
        protected void onPostExecute(String result) {
            mFavorisTask = null;


            super.onPostExecute(result);

            try {

                System.out.println(result);
                JSONObject jObj = new JSONObject(result);

                //System.out.println(result);
                if (jObj.getString("success") != null) {
                    String res = jObj.getString("success");

                    /********************************************/
            /* Si il vaut 1, l'utilisateur est connecté */
                    /********************************************/

                    if (Integer.parseInt(res) == 1) {
                        int salonLength = Integer.parseInt(jObj.getString("taille"));
                        //idTab = new HashMap<String, String>();

                        for (int i = 0; i < salonLength; i++) {

                            JSONObject salonInfo = jObj.getJSONObject(String.valueOf(i));
                            JSONObject salonInfo2 = salonInfo.getJSONObject("favorisList");
                            String salonId = salonInfo2.getString("id");
                            String salonAddress = salonInfo2.getString("address");
                            String salonCP = salonInfo2.getString("codePostal");
                            String salonV = salonInfo2.getString("ville");
                            String salonName = salonInfo2.getString("nom");

                            String addr = salonAddress+", "+salonCP+", "+salonV;

                            Favoris f = new Favoris( salonName, addr);
                            list.add(f);



                        }

                        System.out.println("La taille de la liste "+list.size());

                        //public void fillAdapter(){
                        MyFavorisArrayAdapter adapter = new MyFavorisArrayAdapter(getApplicationContext(), list);
                        System.out.println("Liste construit, la taille est : "+list.size());
                        setListAdapter(adapter);
                        //}


                    }else{
                        Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        /*    if(result["success"] == 1){
                    Toast.makeText(getApplicationContext(), "HTTP POST is working...", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(), "Invalid POST req...", Toast.LENGTH_LONG).show();
                }*/
        }

        @Override
        protected void onCancelled() {
            mFavorisTask = null;
            //    showProgress(false);
        }

    }








}
